package com.itheima.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpQueryParam;
import com.itheima.pojo.PageResult;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Objects;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {

    @Autowired
    private EmpExprMapper empExprMapper;

    /***
     * 员工分页查询
     * @param param
     * @return
     */
    //@Override
    //public PageResult<Emp> pageInfo(EmpQueryParam param) {
    //    //设置分页
    //    IPage<Emp> page = new Page<Emp>(param.getPage(),param.getPageSize());
    //
    //    //实现分页
    //    LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
    //    queryWrapper.like(!Objects.isNull(param.getName()),Emp::getName,param.getName())
    //                .eq(!Objects.isNull(param.getGender()),Emp::getGender,param.getGender())
    //                .between((!Objects.isNull(param.getBegin())  && !Objects.isNull(param.getEnd())),Emp::getEntryDate,param.getBegin(),param.getEnd());
    //    IPage<Emp> pageInfo = getBaseMapper().selectPage(page, queryWrapper);
    //
    //    PageResult<Emp> pageResult = new PageResult<>();
    //    pageResult.setTotal(pageInfo.getTotal());
    //    pageResult.setRows(pageInfo.getRecords());
    //    return pageResult;
    //}


    @Override
    public PageResult<Emp> pageInfo(EmpQueryParam param) {
        //设置分页
        PageHelper.startPage(param.getPage(),param.getPageSize());

        //实现分页
        Page<Emp> pageInfo = (Page<Emp>) getBaseMapper().pageInfo(param);

        PageResult<Emp> pageResult = new PageResult<>();
        pageResult.setTotal(pageInfo.getTotal());
        pageResult.setRows(pageInfo.getResult());
        return pageResult;
    }

    /***
     * 新增员工
     * @param emp
     */
    @Override
    public void saveEmp(Emp emp) {
        //新增员工
        emp.setUpdateTime(LocalDateTime.now());
        emp.setCreateTime(LocalDateTime.now());
        getBaseMapper().insert(emp);

        //新增工作履历
        if(!CollectionUtils.isEmpty(emp.getExprList())){
            //员工ID设置
            emp.getExprList().forEach(expr -> expr.setEmpId(emp.getId()));
            empExprMapper.insertBatch(emp.getExprList());
        }
    }
}
